<?php
class adminAction extends backendAction
{
    public function _initialize() {
        parent::_initialize();
        $this->_mod = D('admin');
        $this->_cate_mod = D('region');
    }

    public function _before_index() {
        $this->assign('roleList',M('admin_role')->where(array('status'=>1))->getField('id,name'));
        $this->list_relation = true;
    }

    public function _before_add() {
        $role_list = M('admin_role')->where('status=1')->select();

        foreach($role_list as $k=>$v){
            $temp[$v['id']] =  $v;
        }
        $role_list = $temp;
        $this->assign('role_list', $role_list);
        $this->assign('customerList',D('customer')->cate_cache());
        if(IS_POST){
            $customerIds = $this->_request('customerIds','trim','');
            if(!empty($customerIds)){
            $_POST['customerIds'] = implode(',',$customerIds);
        }
    }
    }

    public function _before_insert($data='') {
        if( ($data['passWord']=='')||(trim($data['passWord']=='')) ){
            unset($data['passWord']);
        }else{
            $data['passWord'] = md5($data['passWord']);
        }
        if(isset($data['regionId'])){
            $arr = explode('_',$data['regionId']);
            if(count($arr)==2){
                $data['regionId'] = $arr[0];
                $data['storeId']  = $arr[1];
            }
        }
        return $data;
    }

    public function _before_edit() {
        $this->_before_add();
        $id = $this->_request('id','intval',0);
        if(!empty($id)){
            $userHistory = M('userHistory')->where(array('userId'=>$id))->order('historyId desc')->find();
            $userTrain = M('userTrain')->where(array('userId'=>$id))->order('trainId desc')->find();
            $this->assign('userHistory',$userHistory);
            $this->assign('userTrain',$userTrain);
        }
    }

    public function _before_update($data=''){
        if( ($data['passWord']=='')||(trim($data['passWord']=='')) ){
            unset($data['passWord']);
        }else{
            $data['passWord'] = md5($data['passWord']);
        }

        if(isset($data['regionId'])){
            $arr = explode('_',$data['regionId']);
            if(count($arr)==2){
                $data['regionId'] = $arr[0];
                $data['storeId']  = $arr[1];
            }
        }
        return $data;
    }

    public function ajax_check_name() {
        $name = $this->_get('J_userName', 'trim');
        $id = $this->_get('id', 'intval');
        if ($this->_mod->name_exists($name, $id)) {
            echo 0;
        } else {
            echo 1;
        }
    }
    protected function _search() {
        $map = array();
        $status = $this->_request('status', 'trim');
        if($status!=''){
            $map['status'] = $status;
        }
        ($userName = $this->_request('userName', 'trim')) && $map['userName'] = array('like', '%'.$userName.'%');
        ($sim = $this->_request('sim', 'trim')) && $map['sim'] = array('like', '%'.$sim.'%');
        ($simSn = $this->_request('simSn', 'trim')) && $map['simSn'] = array('like', '%'.$simSn.'%');
        ($imei = $this->_request('imei', 'trim')) && $map['imei'] = array('like', '%'.$imei.'%');
        ($roleId = $this->_request('roleId', 'intval')) && $map['roleId'] = $roleId;
        ($id = $this->_request('id', 'intval')) && $map['id'] = $id;
        $regionId = $this->_request('regionId');
        $selected_ids = '';
        if ($regionId) {
            $regionArr = explode('_',$regionId);
            if(count($regionArr)==2){
              $regionId = $regionArr[0];
              $storeId   = $regionArr[1];
              $map['storeId']  = $storeId ;
              $map['regionId'] = $regionId ;
              $spid = $this->_cate_mod->where(array('id'=>$regionId))->getField('spid');
              $selected_ids = $spid ? $spid . $regionId .'|'.$regionId.'_'.$storeId: $regionId.'|'.$regionId.'_'.$storeId;
            }else{
                $id_arr = $this->_cate_mod->get_child_ids($regionId, true);
                $map['regionId'] = array('IN', $id_arr);
                $spid = $this->_cate_mod->where(array('id'=>$regionId))->getField('spid');
                $selected_ids = $spid ? $spid . $regionId : $regionId;
            }
        }
        $admin = getUserSession();
        if(!empty($admin['regionId'])){
            $id_arr = $this->_cate_mod->get_child_ids($admin['regionId'], true);        
            $map['regionId'] = array('in',$id_arr);
            //$map['regionId']
        }     
        $this->assign('search', array(
            'time_start' => $time_start,
            'time_end' => $time_end,
            'cateId' => $cateId,
            'selected_ids' => $selected_ids,
            'status'  => $status,
            'keyword' => $keyword,
            'roleId'=>$roleId,
            'id'=>$id,
        ));
        //print_r($map);
        return $map;
    }



    /**
     * 瀵煎叆鍛樺伐璁惧淇℃伅
     *
     */
	public function importDeviceInfo(){
		$this->display();
	}

	/**
	 * 瀵煎叆鍛樺伐鎸佹湁鐨勮澶囦俊鎭?
	 * 琛?pad_sim "pad璁惧鐨凷IM淇℃伅琛?
	 * 琛?pad_imei "pad璁惧鐨処MEI淇℃伅"
	 */
    public function uploadDeviceInfo(){
        if(count($_FILES) > 0){
    		//is_uploaded_file 鈥?鍒ゆ柇鏂囦欢鏄惁鏄€氳繃 HTTP POST 涓婁紶鐨?
			if(is_uploaded_file($_FILES["excel"]["tmp_name"])){

				$file = $_FILES["excel"]["tmp_name"];

				if(is_file($file)){
					//璇诲彇鏂囦欢鍐呭
					$res = readExcelFile($file);
					if(is_array($res)){
						foreach ($res as $row){
							//瀵煎叆鍒? pad_sim 琛ㄤ腑
							if($row['sim'] != '' && $row['simSn'] != ''){
								$data['sim']	= $row['sim'];
								$data['simSn']	= $row['simSn'];

								//鍒ゆ柇鏄惁宸茬粡瀛樺湪鐩稿悓 sim 鍊肩殑鏁版嵁
								$old_info = '';
								$old_info = M('pad_sim')->where("sim={$row['sim']}")->find();
								if($old_info){
									//鍒ゆ柇杩欐潯鏃ф暟鎹紝鏄惁杩樻湭琚粦瀹?
									if($old_info['ref']==0){
										M('pad_sim')->where("sim={$row['sim']}")->save($data);	//淇敼鏁版嵁
									}
								}else{
									M('pad_sim')->add($data);	//娣诲姞鏁版嵁
								}
							}
							//瀵煎叆鍒? pad_imei 琛ㄤ腑
							if($row['imei'] != ''){
								$data['imei'] = $row['imei'];
								//鍒ゆ柇鏄惁宸茬粡瀛樺湪鐩稿悓 imei 鍊肩殑鏁版嵁
								$old_info = '';
								$old_info = M('pad_imei')->where("imei={$row['imei']}")->find();
								//濡傛灉涓嶅瓨鍦紝鍒欐坊鍔?
								if( ! $old_info ){
									M('pad_imei')->add($data);	//娣诲姞鏁版嵁
								}
							}
						}
						$this->ajaxReturn(1, L('operation_success'));
					}
				}
			}else{
				$this->ajaxReturn(0, L('placeUploadFile'));
			}
    	}else{
    		$this->ajaxReturn(0, L('placeUploadFile'));
    	}
    }


    /**
     * 鍛樺伐璁惧sim 鍒楄〃
     */

     public function simDeviceList(){
        $this->display();
     }

     /**
      * 鍛樺伐璁惧imei 鍒楄〃
      */
     public function imeiDeviceList(){
        $this->_name = 'pad_imei';
        $this->index();

     }
	 
	/**
	 * 个人资料
	 */ 
	public function slef(){
		if(IS_POST){
			$newPassword = I('newPassword');
			$confirmPassword = I('confirmPassword');
			$email = I('email');
			$phone = I('phone');

			$data = array();

			if($newPassword){
				if($newPassword == $confirmPassword){
					$data['password'] = md5($newPassword);
				}else{
					$this->error(L('两次输入的密码不一致'));
				}
			}

			if($email){
				$data['email'] = $email;
			}

			if($phone){
				$data['phone'] = $phone;
			}

			if($data){
				D('admin')->where(array('id'=> getAdminId()))->save($data);
				$this->success(L('operation_success'));
			}else{
				$this->error(L('operation_failure'));
			}
			
		}else{
			// 个人信息，个人姓名、所在地市、片区、厅店、职位
			$field = array(
				'admin.userName',
				'admin.realName',
				'admin.jobPost',
				'admin.email',
				'admin.phone',
				'city.name'=>'cityName',
				'microArea.name'=>'microAreaName',
				'store.name'=>'storeName',
			);
			$info = D('admin')->alias('admin')->field($field)
					->join(C('DB_PREFIX')."store AS store ON store.id = admin.storeId")
					->join(C('DB_PREFIX')."admin_role AS role ON role.id = admin.roleId")
					->join(C('DB_PREFIX')."region AS microArea ON microArea.id = admin.regionId")
					->join(C('DB_PREFIX')."region AS city ON city.id = microArea.pid")
					->where(array('admin.id'=>getAdminId()))
					->find();
			
			$this->assign('info', $info);
			$this->display();
		}
	}

}